import { Component, OnInit,ChangeDetectorRef,ViewChild } from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/observable/fromEvent';
import {DataSource} from '@angular/cdk/collections';
import {MdPaginator, MdSnackBar, MD_DIALOG_DATA} from "@angular/material";
import {ApiServiceService} from '../api.service'
import {MdDialog, MdDialogRef} from '@angular/material';
import { DialogService,DeleteManaConfirm } from "../service/dialog.service";

@Component({
  selector: 'app-acceptor',
  templateUrl: './acceptor.component.html',
  styleUrls: ['./acceptor.component.css']
})
export class AcceptorComponent implements OnInit {

  constructor(private apiService:ApiServiceService,
              private dialogService: DialogService,
              private changeDetectorRef:ChangeDetectorRef,
              public snackBar:MdSnackBar,
              public dialog:MdDialog) {
  }

  DEVNUMS = [
    {id:'43415230000000301010201',value:"舒城县调频广播适配器"},
    {id:'43415230000000302010201',value:"舒城县有线数字电视适配器"},
    {id:'43415230000000303010201',value:"舒城县地面数字电视适配器"},
    {id:'43415231000000314010201',value:"舒城县应急广播大喇叭适配器"},
  ]
  displayedColumns = ['deleteFlag', /*'no',*/ 'EBRID', 'EBRName', 'URL', 'Longitude','Latitude', "StateDesc", 'operation'];
  soundSourceDatabase = new SoundSourceDatabase();
  dataSource:SoundSourceDataSource | null;
  allSelectedFlag:boolean;

  @ViewChild(MdPaginator) paginator:MdPaginator;

  acceptorInfo:Object={};
  acceptorList:Array<any>;
  acceptorHead:Array<any>;
  noneText:string='';
  ngOnInit() {

    this.dataSource = new SoundSourceDataSource(this.soundSourceDatabase, this.paginator);
    this.changeDetectorRef.detectChanges();
    this.allSelectedFlag = false;
    //this.apiService.getAcceptor().sub
    this.apiService.getAllInfo('EBRAS').subscribe(res=>{
      if(res.success){
        this.acceptorInfo=res.data;
        this.acceptorList=res.data.content;
        this.acceptorHead=res.data.header;
        this.soundSourceDatabase.refreshData(this.acceptorList);
        console.log(this.acceptorList)
      }else{
        this.dialogService.openSnackBar("初始化失败，请重试！","");
      }
      err=>{
        this.apiService.doError(err);
        this.noneText="服务器故障，请刷新"
      }
    })


  }
  add() {
    let stationitem={EBRID:'',EBRName:'',URL:'',status:'',Longitude:'',Latitude:'',isEdit:true,isNew:true}
    this.acceptorList.push(stationitem)
    this.soundSourceDatabase.refreshData(this.acceptorList);

  }
  refresh(){
    this.ngOnInit();
  }

  edit(row){
    row.isEdit=true;
  }


  allSelected(event) {
    if (event.checked) {
      this.soundSourceDatabase.data.forEach(function (e) {
        e.isChecked = true;
        console.log(e)
      })
    } else {
      this.soundSourceDatabase.data.forEach(function (e) {
        e.isChecked = false;
      })
    }

  }

  reportAll(){
    console.log('快上报！')
    let data = [];
    this.acceptorList.map(item=>{
      if(item.isChecked){
        data.push(item.EBRID)
      }
    })


    this.apiService.reportEom("EBRAS",data).subscribe(res =>{
      console.log(res);
      setTimeout(()=>{
        if(res.success){
          this.openSnackBar("上报成功。", "");
        }else{
          this.openSnackBar("上报失败,请稍后再试。", "");
        }

      },2000);

    });
  }

  reportStatus() {
    let data = [];
    this.acceptorList.map(item=>{
      if(item.isChecked){
        data.push(item.EBRID)
      }
    })

    this.apiService.reportEomStatus("EBRAS",data).subscribe(res =>{
      console.log(res);
      setTimeout(()=>{
        if(res.success){
          this.openSnackBar("上报成功。", "");
        }else{
          this.openSnackBar("上报失败,请稍后再试。", "");
        }
      });
    });
  }

  finish(row) {
    if(row.isNew){
   if(row.EBRID!=""&&row.EBRName!=""&& row.URL!=""&&row.Longitude!=""&&row.Latitude!="") {

     console.log('这里是我荣威')
     this.apiService.addEom("EBRAS", row).subscribe(res => {

       if (res.success) {
         this.openSnackBar("添加成功。", "");
         row.isEdit = false;
         row.isNew = false;
         this.refresh();
       } else {
         this.openSnackBar("res.err。", "");
       }
     })
   }else{
     this.openSnackBar("文本不能为空", "")
   }
    }else{
      this.apiService.updateEom("EBRAS",row).subscribe(res => {
        console.log(res);
        if (res.success) {
          this.openSnackBar("修改成功。", "");
          row.isEdit = false;
        } else {
          this.openSnackBar("res.err。", "");
        }
      })
    }

  }

  delete(row) {
    // debugger;
    this.dialogService.openDeleteConfirm()
      .afterClosed()
      .subscribe(res => {
        if(res) {
          this.apiService.deleteEom("EBRAS",[row._id]).subscribe(res => {
            if (res.success) {
              this.openSnackBar("删除成功。", "");
              row.isEdit = false;
              this.refresh();
            } else {
              this.openSnackBar(res.error, "");
            }
          })
        }
      })
  }


  report(row) {
    let formData = new FormData();
    formData.append("EBMID", row.EBMID);
    this.apiService.reportInfo(formData)
        .subscribe(res=> {
          setTimeout(()=> {
            if (res.success) {
              this.openSnackBar("上报成功。", "");
            } else {
              this.openSnackBar("上报失败,请稍后再试。", "");
            }
          }, 3000)
        });
  }


  editGroup(row){


  }

    openSnackBar(message:string, action:string) {
    this.snackBar.open(message, action, {
      duration: 3000,
    });
  }
}


const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

/*export interface SoundSourceData {
 deleteFlag:boolean;
 no:string;
 acaption:string;
 acontent:string;
 uid:string;
 isChecked:boolean,
 id: 'EBMID',
 name: 'ID'
 },
 {
 id: "MsgTitle",
 name: "标题"
 },
 {
 id: "SenderName",
 name: "机构名称"
 },
 {
 id: 'StartTime',
 name: '发布时间',
 },
 {
 id: 'BrdStateDesc',
 name: '状态'
 },
 {
 id: 'oper',
 name: '操作'

 }*/
export interface SoundSourceData {
  deleteFlag:boolean;
  // no:string;
  EBRID:string;
  EBRName:string;
  URL:string;
 // status:string;
  Longitude:string;
  Latitude:string;
  operation?:any
  isChecked:boolean,
}

export class SoundSourceDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange:BehaviorSubject<SoundSourceData[]> = new BehaviorSubject<SoundSourceData[]>([]);

  get data():SoundSourceData[] {
    return this.dataChange.value;
  }


  constructor() {
    // Fill up the database with 100 users.
    var _a:SoundSourceData[] = [
      // {
      //   "deleteFlag": false,
      //   "no": "1",
      //   "acaption": "网络节目源1",
      //   "acontent": "7001",
      //   "uid": "admin",
      //   "isChecked": false
      //
      // }
    ];
    this.dataChange.next(_a);


    // for (var i = 0; i < 100; i++) {
    //   this.addUser();
    // }
  }


  refreshData(array) {
    array.forEach(function (item, index) {
      item.no = index + 1;
    })
    this.dataChange.next(<SoundSourceData[]> array);
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      deleteFlag: false,
      no: (this.data.length + 1).toString(),
      EBRID: name,
      EBRName: Math.round(Math.random() * 100).toString(),
      URL: COLORS[Math.round(Math.random() * (COLORS.length - 1))],
 //     status: (this.data.length + 1).toString(),
      Longitude: name,
      Latitude: Math.round(Math.random() * 100).toString(),

      operation: (this.data.length + 1).toString(),
      isChecked: false,
    };
  }
}

export class SoundSourceDataSource extends DataSource<any> {
  constructor(private _soundSourceDatabase:SoundSourceDatabase, private _paginator:MdPaginator) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect():Observable<SoundSourceData[]> {
    const displayDataChanges = [
      this._soundSourceDatabase.dataChange,
      this._paginator.page,
    ];
    return Observable.merge(...displayDataChanges).map(() => {
      const data = this._soundSourceDatabase.data.slice();

      // Grab the page's slice of data.
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      return data.splice(startIndex, this._paginator.pageSize);
    });

  }

  disconnect() {
  }
}
